import React, { useState } from "react";
import { Layout, Card, Input, Radio, Checkbox, Button, message, Spin, Select } from "antd";
import { SmileOutlined } from "@ant-design/icons";
import "./SurveyPage.scss";

const SurveyPage = () => {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    age: "",
    investmentGoal: "",
    expectedReturn: "",
    redemptionNeed: "",
    riskAcceptance: "",
    incomeSource: "",
    annualIncome: "",
    investableProportion: "",
    debtStatus: "",
    investmentKnowledge: "",
    investmentExperience: "",
    investmentDuration: "",
    preferredProducts: [],
    lossTolerance: "",
  });

  const { Header, Content, Footer } = Layout;

  const handleInputChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSelectChange = (name, value) => {
    setFormData({ ...formData, [name]: value });
  };

  const handleCheckboxChange = (checkedValues) => {
    setFormData({ ...formData, preferredProducts: checkedValues });
  };

  const handleSubmit = () => {
    const isComplete = Object.values(formData).every((value) => {
      if (Array.isArray(value)) {
        return value.length > 0;
      }
      return value !== "";
    });

    console.log("表单数据:", formData);

    if (!isComplete) {
      message.error("请完整填写问卷后再提交！");
      return;
    }
    
    // 提交数据到/api/privacy/risk-profile
    // 调用privacyApi.js中的$submitSurvey函数
    setLoading(true);
    import("../../api/privacyApi").then(({ $submitSurvey }) => {
      $submitSurvey(formData)
        .then((response) => {
          message.success("问卷提交成功！");
          setLoading(false);
          // 可以在这里重置表单或进行其他操作
          setFormData({
            age: "",
            investmentGoal: "",
            expectedReturn: "",
            redemptionNeed: "",
            riskAcceptance: "",
            incomeSource: "",
            annualIncome: "",
            investableProportion: "",
            debtStatus: "",
            investmentKnowledge: "",
            investmentExperience: "",
            investmentDuration: "",
            preferredProducts: [],
            lossTolerance: "",
          });
        })
        .catch((error) => {
          message.error("问卷提交失败，请稍后再试！");
          console.error("提交失败:", error);
          setLoading(false);
        });
    });
  };

  return (
    <Layout className="survey-layout">
      <Header className="header">
        <div className="header-title">
          <SmileOutlined style={{ marginRight: "8px" }} />
          投资者风险能力评测
        </div>
      </Header>
      <Content className="content">
        {loading ? (
          <div className="loading-container">
            <Spin tip="提交中..." size="large" />
          </div>
        ) : (
          <Card className="survey-card">
            <form className="survey-form">
              {/* 1. 年龄 */}
              <div className="form-item">
                <label>1. 您的年龄是？</label>
                <Radio.Group
                  name="age"
                  value={formData.age}
                  onChange={handleInputChange}
                >
                  <Radio value="under_18">18周岁以下</Radio>
                  <Radio value="18_30">18-30</Radio>
                  <Radio value="31_40">31-40</Radio>
                  <Radio value="41_50">41-50</Radio>
                  <Radio value="51_64">51-64</Radio>
                  <Radio value="65_above">年满或高于65岁</Radio>
                </Radio.Group>
              </div>

              {/* 2. 投资目标 */}
              <div className="form-item">
                <label>2. 您的投资目标是？</label>
                <Radio.Group
                  name="investmentGoal"
                  value={formData.investmentGoal}
                  onChange={handleInputChange}
                >
                  <Radio value="education_retirement">子女教育费，退休计划</Radio>
                  <Radio value="personal_goals">个人目标（如置业、购车）</Radio>
                  <Radio value="wealth_growth">让财富保值增值</Radio>
                </Radio.Group>
              </div>

              {/* 3. 期望的投资回报 */}
              <div className="form-item">
                <label>3. 您期望的投资回报是？</label>
                <Radio.Group
                  name="expectedReturn"
                  value={formData.expectedReturn}
                  onChange={handleInputChange}
                >
                  <Radio value="same_as_deposit">跟银行存款利率大体相同</Radio>
                  <Radio value="slightly_higher">比定期存款利率稍高</Radio>
                  <Radio value="much_higher">远超过定期存款利率</Radio>
                </Radio.Group>
              </div>

              {/* 4. 是否需要赎回 */}
              <div className="form-item">
                <label>4. 您在金融产品持有期内是否有赎回产品的需求？</label>
                <Radio.Group
                  name="redemptionNeed"
                  value={formData.redemptionNeed}
                  onChange={handleInputChange}
                >
                  <Radio value="yes">有</Radio>
                  <Radio value="not_sure">不确定</Radio>
                  <Radio value="no">没有</Radio>
                </Radio.Group>
              </div>

              {/* 5. 不保本型产品风险 */}
              <div className="form-item">
                <label>
                  5. 对于不保本型金融产品，您可能无法获得任何收益且无法收回全部本金。您是否了解并接受？
                </label>
                <Radio.Group
                  name="riskAcceptance"
                  value={formData.riskAcceptance}
                  onChange={handleInputChange}
                >
                  <Radio value="yes">是</Radio>
                  <Radio value="no">否</Radio>
                </Radio.Group>
              </div>

              {/* 6. 主要收入来源 */}
              <div className="form-item">
                <label>6. 您的主要收入来源是？</label>
                <Select
                  name="incomeSource"
                  placeholder="请选择"
                  value={formData.incomeSource}
                  onChange={(value) => handleSelectChange("incomeSource", value)}
                  style={{ width: '200px' }} // 设置下拉栏的宽度
                  options={[
                    { label: "工资、劳务报酬", value: "salary" },
                    { label: "生产经营所得", value: "business_income" },
                    { label: "金融性资产收入", value: "financial_income" },
                    { label: "非金融性资产收入", value: "non_financial_income" },
                    { label: "无固定收入", value: "no_fixed_income" },
                  ]}
                />
              </div>

              {/* 7. 年收入 */}
              <div className="form-item">
                <label>7. 您的年收入大致为？</label>
                <Select
                  name="annualIncome"
                  placeholder="请选择年收入范围"
                  value={formData.annualIncome}
                  onChange={(value) => handleSelectChange("annualIncome", value)}
                  style={{ width: '200px' }} // 设置下拉栏的宽度
                  options={[
                    { label: "5万元以下", value: "under_50k" },
                    { label: "5万到20万元", value: "50k_200k" },
                    { label: "20万元以上", value: "200k_above" },
                  ]}
                />
              </div>


              {/* 8. 可投资资产占比 */}
              <div className="form-item">
                <label>8. 您用于投资的资产占比大约为？</label>
                <Radio.Group
                  name="investableProportion"
                  value={formData.investableProportion}
                  onChange={handleInputChange}
                >
                  <Radio value="under_20%">20%以下</Radio>
                  <Radio value="20%-50%">20%-50%</Radio>
                  <Radio value="above_50%">50%以上</Radio>
                </Radio.Group>
              </div>

              {/* 9. 负债情况 */}
              <div className="form-item">
                <label>9. 您目前的负债情况是？</label>
                <Radio.Group
                  name="debtStatus"
                  value={formData.debtStatus}
                  onChange={handleInputChange}
                >
                  <Radio value="none">无负债</Radio>
                  <Radio value="manageable">负债率较低，可控范围内</Radio>
                  <Radio value="high">负债率较高，有一定风险</Radio>
                </Radio.Group>
              </div>

              {/* 10. 投资知识 */}
              <div className="form-item">
                <label>10. 您的投资知识水平是？</label>
                <Radio.Group
                  name="investmentKnowledge"
                  value={formData.investmentKnowledge}
                  onChange={handleInputChange}
                >
                  <Radio value="none">无相关知识</Radio>
                  <Radio value="basic">基础知识</Radio>
                  <Radio value="proficient">较专业</Radio>
                </Radio.Group>
              </div>

              {/* 11. 投资经验 */}
              <div className="form-item">
                <label>11. 您的投资经验是？</label>
                <Radio.Group
                  name="investmentExperience"
                  value={formData.investmentExperience}
                  onChange={handleInputChange}
                >
                  <Radio value="none">无经验</Radio>
                  <Radio value="limited">有限经验</Radio>
                  <Radio value="rich">丰富经验</Radio>
                </Radio.Group>
              </div>

              {/* 12. 投资期限 */}
              <div className="form-item">
                <label>12. 您能接受的投资期限是？</label>
                <Radio.Group
                  name="investmentDuration"
                  value={formData.investmentDuration}
                  onChange={handleInputChange}
                >
                  <Radio value="short_term">短期（1年以内）</Radio>
                  <Radio value="medium_term">中期（1-3年）</Radio>
                  <Radio value="long_term">长期（3年以上）</Radio>
                </Radio.Group>
              </div>

              {/* 13. 偏好产品 */}
              <div className="form-item">
                <label>13. 您更倾向于以下哪些产品？（可多选）</label>
                <Checkbox.Group
                  options={[
                    { label: "储蓄型产品", value: "savings" },
                    { label: "基金", value: "fund" },
                    { label: "股票", value: "stocks" },
                    { label: "期货", value: "futures" },
                    { label: "其他", value: "others" },
                  ]}
                  value={formData.preferredProducts}
                  onChange={handleCheckboxChange}
                />
              </div>

              {/* 14. 投资态度 */}
              <div className="form-item">
                <label>14. 您对投资亏损的态度是？</label>
                <Radio.Group
                  name="lossTolerance"
                  value={formData.lossTolerance}
                  onChange={handleInputChange}
                >
                  <Radio value="very_sensitive">非常敏感</Radio>
                  <Radio value="neutral">能接受小幅波动</Radio>
                  <Radio value="risk_taker">愿意承担较高风险</Radio>
                </Radio.Group>
              </div>

              <Button type="primary" onClick={handleSubmit} className="submit-button">
                提交问卷
              </Button>
            </form>
          </Card>
        )}
      </Content>
      <Footer className="footer">© 2025 问卷调查页面 | 基于 Ant Design 设计</Footer>
    </Layout>
  );
};

export default SurveyPage;
